package com.zj.leetcode.medium.tree;

/**
 * @program: algorithm
 * @description: 二叉搜索树中第K小的元素
 * 230 kth-smallest-element-in-a-bst
 * @author: Zhang Bo
 * @create: 2022-07-08 17:25:13
 **/
public class KthSmallestElementInABst {
    public static void main(String[] args) {
        Solution solution = new KthSmallestElementInABst().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public int kthSmallest(TreeNode root, int k) {
            if(root == null){
                return 0;
            }
            this.dfs(root, k);
            return ret;
        }

        int num = 0;
        int ret = 0;
        private void dfs(TreeNode node, int k) {
            if (node != null) {
                if (node.left != null) {
                    this.dfs(node.left, k);
                }
                num++;
                if(num == k){
                    ret = node.val;
                }
                if (node.right != null) {
                    this.dfs(node.right, k);
                }
            }
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
